package cn.my.learning.service;

import cn.my.learning.domain.LibraryList;
import cn.my.learning.domain.User;
import cn.my.learning.repository.LibraryListRepository;
import cn.my.learning.repository.UserRepository;
import cn.my.learning.util.PageableTools;
import cn.my.learning.util.PwdEnAndDecode;
import com.mongodb.WriteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/3/30.
 * 用户操作服务层
 */
@Repository
public class UserServiceImpl {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LibraryListRepository libraryListRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户登录
     * @param account 账号
     * @param password 密码
     * @return
     */
    public List<User> findByAccountAndPassword(String account, String password) {
        PwdEnAndDecode pwdEnAndDecode = new PwdEnAndDecode();
        return userRepository.findByAccountAndPassword(account,pwdEnAndDecode.encode(password));
    }

    /**
     * 更新账户密码
     * @param account
     * @param password
     * @return
     */
    public boolean updatePassword(String account, String password) {
        PwdEnAndDecode pwdEnAndDecode = new PwdEnAndDecode();
        //查询出where传过来的文章在数据库是否有这个对象
        Query query = Query.query(Criteria.where("account").is(account));

        String newPassword= pwdEnAndDecode.encode(password);

        //编写Update操作
        Update update = Update.update("password",newPassword);

        //执行查询语句并update
        WriteResult writeResult = mongoTemplate.updateFirst(query, update, User.class);

        return writeResult.isUpdateOfExisting();
    }


    /**
     * 通过账号查找用户信息
     * @param account 账号
     * @return
     */
    public List<User> findByAccount(String account) {
        return userRepository.findByAccount(account);
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    public boolean addUser(User user) {
        PwdEnAndDecode pwdEnAndDecode = new PwdEnAndDecode();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//可以方便地修改日期格式
        user.setRegisteredDate(dateFormat.format(now));
        user.setPassword(pwdEnAndDecode.encode(user.getPassword()));
        userRepository.save(user);
        return true;
    }

    /**
     * 获取用户收藏文章
     * @param articleCollection //用户收藏文章id的数组
     * @return
     */
    public List<LibraryList> findarticleCollection(List<String> articleCollection){
        List list=new ArrayList();
        for (int num=0;num<articleCollection.size();num++){
            list.addAll(libraryListRepository.findByarticleCode(articleCollection.get(num).toString()));
        }
        return list;
    }

    /**
     * 获取用户自己写的文章
     * @param account 用户账号
     * @param current 页数
     * @return
     */
    public Page<LibraryList> findUserArticle(String account,int current){
        Pageable pageable = PageableTools.addTimeSortForDescMyArc(current, 10);
        return libraryListRepository.findBypublisherAccount(account,pageable);
    }

    /**
     * 修改密码
     * @param account
     * @param newPassword
     * @return
     */
    public boolean modifyUserPassword(String account, String newPassword){
        PwdEnAndDecode pwdEnAndDecode = new PwdEnAndDecode();
        String password= pwdEnAndDecode.encode(newPassword);
        Query query = Query.query(Criteria.where("account").is(account));
        Update update = Update.update("password", password);
        WriteResult writeResult = mongoTemplate.updateFirst(query, update, User.class);
        return writeResult.isUpdateOfExisting();
    }

    /**
     * 验证账号和邮箱是否匹配
     * @param userAccount
     * @return
     */
    public List<User> findUserEmailAddressByUserAccount(String userAccount){
        //验证用户及其邮箱是否匹配
        Criteria criteria = Criteria.where("account").is(userAccount);
        return mongoTemplate.find(new Query(criteria), User.class);
    }

    /**
     * 通过账号寻找用户名
     * @param account
     * @return
     */
    public User findUsernameByAccount(String account){
        return userRepository.findUsernameByAccount(account);
    }

    /**
     * 更新用户状态
     * @param account
     * @param remoteAddress
     * @param sessionID
     * @return
     */
    public boolean UpdateLoginStatus(String account, String remoteAddress, String sessionID){
        //Query语句
        Query query = Query.query(Criteria.where("account").is(account));

        //编写Update操作
        Update update = Update.update("recentLoginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                              .set("recentLoginAddress", remoteAddress)
                              .set("isLoginNow", true)
                              .set("sessionId", sessionID);

        WriteResult writeResult = mongoTemplate.upsert(query, update, User.class);

        return writeResult.isUpdateOfExisting();
    }

    /**
     * 修改登录状态
     * @param account
     * @return
     */
    public boolean LogoutStatus(String account){
        //Query语句
        Query query = Query.query(Criteria.where("account").is(account));

        //编写Update操作
        Update update = Update.update("recentLoginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                .set("isLoginNow", false);

        WriteResult writeResult = mongoTemplate.upsert(query, update, User.class);

        return writeResult.isUpdateOfExisting();
    }
}
